<template>
  <div class="allsearch">
    <section class="search-content">
      <el-row :gutter="4" type="flex" justify="start">
        <el-col :span="22">
          <el-input
            v-model="username"
            placeholder="学习卡批次名称"
            style="width:200px;"
            @keyup.enter.native="handleFilter"
          />
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </el-col>
        <el-col :span="2">
          <div style="width:100%;">
            <el-button type="primary" style="float:right;" @click="addCard = true;addCardData = {codeByte: '16'}">生成学习卡</el-button>
          </div>
        </el-col>
      </el-row>
    </section>
    <subtable
      :table-label="cardLabel"
      :table-data="cardData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="button" :min-width="100" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-dropdown
            trigger="click"
            split-button
            type="primary"
            @command="handleCommand($event,scope)"
            @click="handleClickExport(scope)"
          >
            导出
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">查看详情</el-dropdown-item>
              <!--<el-dropdown-item command="2">获取发放地址</el-dropdown-item>-->
              <el-dropdown-item v-if="scope.row.status === 'abolish'" command="3">启用本批次</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'normal'" command="4">作废本批次</el-dropdown-item>
              <el-dropdown-item command="5">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </subtable>

    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <!-- 获取发放地址 -->
    <el-dialog :visible.sync="dialog" title="获取发放地址" width="580px">
      <el-form label-width="160px">
        <el-form-item label="学习卡批次名称">
          <el-input v-model="issueAddress.batchName" :disabled="true" style="width:300px;"/>
        </el-form-item>
        <el-form-item label="发 放 地 址">
          <el-input v-model="issueAddress.batchUrl" style="width:300px;" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="tag-read" style="float:left" type="primary" @click="handleCopy">复制</el-button>
        <el-button type="primary" @click="dialog = false;issueAddress = {}">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 生成学习卡 -->
    <el-dialog :visible.sync="addCard" title="生成学习卡" width="640px">
      <el-form ref="addCardData" :model="addCardData" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="学习卡批次名称" prop="name">
          <el-input v-model="addCardData.name" style="width:200px;"/>
          <span style="margin-left:20px;color:#737373">如:100学习币充值卡</span>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程分类选择" prop="categoryId">
          <treeselect v-model="addCardData.categoryId" :multiple="false" :options="courseCategorys" style="width: 200px"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="批次说明">
          <el-input v-model="addCardData.batchExplain" style="width:200px;"/>
          <span style="margin-left:20px;color:#737373">用于说明本批次学习卡，内容可选填</span>
        </el-form-item>
        <!--<el-form-item :label-width="formLabelWidth" :label="virtualCurrencyName ? virtualCurrencyName : '虚拟币'" prop="rate">-->
        <!--<el-input v-model="addCardData.rate" style="width:200px;"/>-->
        <!--<span style="margin-left:20px;color:#737373">学习卡可充值获得的农商币数量</span>-->
        <!--</el-form-item>-->
        <el-form-item :label-width="formLabelWidth" label="生成数量" prop="number">
          <el-input v-model="addCardData.number" style="width:200px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="学习卡前缀" prop="prefix">
          <el-input v-model="addCardData.prefix" style="width:200px;"/>
          <span style="margin-left:20px;color:#737373">学习卡前缀用于区分学习卡，不可重复</span>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="有效期" prop="endTime">
          <el-date-picker
            v-model="addCardData.endTime"
            type="datetime"
            placeholder="最后期限"
            style="width:200px;"
          />
          <span style="margin-left:20px;color:#737373">学习卡到期日期</span>
        </el-form-item>
        <!--<div class="foot">-->
        <!--<ul>-->
        <!--<li style="text-indent:60px;">学习卡为16位数字卡号</li>-->
        <!--<li style="text-indent:60px;">密码为16位字母数字组合</li>-->
        <!--<li style="text-indent:60px;">学员使用时只需要输入密码即可</li>-->
        <!--</ul>-->
        <!--</div>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCard = false">取 消</el-button>
        <el-button type="primary" @click="addStudyCard">生成学习卡</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import Clipboard from 'clipboard'
  import Pagination from '@/components/Pagination' // 分页组件
  import Subtable from '@/components/Eltable'
  import {addStudyCard, deleteBatchStudyCard, getCardList, getListByBatchId, getVirtualCurrencyName, updateStudyCard} from '@/api/operate/learnCard' // 接口
  import {getTenantId, getUserId, getUserName} from '@/utils/auth'
  import {parseTime} from '@/utils'
  import {categoryList} from '@/api/user/user'; // 数据接口
  export default {
    components: {
      Pagination,
      Subtable,
      Treeselect
    },
    data() {
      return {
        downloadLoading: false,
        dialog: false,
        issueAddress: {
          batchName: '',
          batchUrl: ''
        },
        courseCategorys: [],
        formLabelWidth: '130px',
        total: 0,
        currentpage: 1,
        pagesize: 10,
        virtualCurrencyName: '',
        addCard: false,
        addCardData: {
          name: '',
          batchExplain: '',
          rate: '',
          number: '',
          prefix: '',
          endTime: '',
          codeByte: '',
          categoryId: ''
        },
        username: '',
        rules: {
          categoryId: [{required: true, message: '不能为空', trigger: 'blur'}],
          name: [{required: true, message: '不能为空', trigger: 'blur'}],
          rate: [{required: true, message: '不能为空', trigger: 'blur'}],
          number: [{required: true, message: '不能为空', trigger: 'blur'}],
          prefix: [{required: true, message: '不能为空', trigger: 'blur'}],
          endTime: [{required: true, message: '不能为空', trigger: 'blur'}]
        },
        cardLabel: [{label: '批次id', width: '', prop: 'id'}, {label: '批次名称', width: '', prop: 'name'}, {label: '面额', width: '', prop: 'rate'}, {label: '生成张数', width: '', prop: 'number'}, {label: '有效期', width: '', prop: 'endTimeTimeStr'}, {label: '生成者', width: '', prop: 'userName'}, {label: '状态', width: '', prop: 'statusStr'}],
        listFilter: [],
        cardData: []
      }
    },
    mounted() {
      this.getData()
      this.getVirtualCurrencyName()
      this.getCourseCategorys()
    },
    methods: {
      getCourseCategorys() {
        categoryList('course', getTenantId()).then(response => {
          this.courseCategorys = response.data.items
        }).catch(() => {
        })
      },
      getVirtualCurrencyName() {
        getVirtualCurrencyName(getTenantId()).then(res => {
          this.virtualCurrencyName = res.data.name
        })
      },
      handleCommand(command, scope) {
        if (command === '1') {
          getListByBatchId(scope.row.id).then(res => {
            this.$emit('singleUsedCard', res.data.items)
          })
        } else if (command === '3') {
          scope.row.status = 'normal'
          this.updateStudyCard(scope.row, '启用')
        } else if (command === '4') {
          scope.row.status = 'abolish'
          this.updateStudyCard(scope.row, '作废')
        } else if (command === '5') {
          this.deleteStudyCard(scope.row)
        }
      },
      handleCopy() {
        // 复制地址
        new Clipboard('.tag-read', {
          text: function () {
            return this.issueAddress.batchUrl
          }
        })
        this.$message({
          type: 'success',
          message: '复制成功'
        })
      },
      handleClickExport(scope) {
        // 导出学习卡
        getListByBatchId(scope.row.id).then(res => {
          res.data.items.map(item => {
            if (item.batchStatus === 'normal') item.batchStatusStr = '正常'
            if (item.batchStatus === 'abolish') item.batchStatusStr = '作废'
          })
          const list = res.data.items
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['批次', '状态', '账号', '密码']
            const filterVal = ['batchName', 'batchStatusStr', 'cardId', 'cardPassword']
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: 'learnCardList',
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.downloadLoading = false
          })
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'endTime' || j === 'startTime') {
            return v[j] ? parseTime(v[j]) : v[j]
          } else {
            return v[j]
          }
        }))
      },
      handleFilter() {
        this.cardData = this.listFilter.filter(item => {
          if (this.username && item.name.toLowerCase().indexOf(this.username.toLowerCase()) === -1) return false
          return true
        })
        this.total = this.cardData.length
      },
      clearParams() {
        this.username = ''
        this.getData()
      },
      getData() {
        this.listLoading = true
        getCardList('studyCard').then(response => {
          this.cardData = response.data.items.filter(item => {
            if (item.tenantId !== getTenantId()) return false
            return true
          })
          this.cardData.map(item => {
            if (item.status === 'normal') item.statusStr = '正常'
            if (item.status === 'abolish') item.statusStr = '作废'
          })
          this.listFilter = this.cardData
          this.total = this.cardData.length
        })
      },
      updateStudyCard(row, event) {
        updateStudyCard(row).then(res => {
          this.$notify({
            title: '成功',
            message: `学习卡已${event}`,
            type: 'success',
            duration: 2000
          })
          this.getData()
        })
      },
      addStudyCard() {
        this.$refs.addCardData.validate(valid => {
          if (valid) {
            if (!this.addCardData.categoryId) {
              this.$message.error('请选择分类!')
            } else {
              this.addCard = false
              this.addCardData.batchType = 'studyCard'
              this.addCardData.status = 'normal'
              this.addCardData.userId = getUserId()
              this.addCardData.userName = getUserName()
              this.addCardData.tenantId = getTenantId()
              addStudyCard(this.addCardData).then(() => {
                this.$notify({
                  title: '成功',
                  message: '学习卡已创建！',
                  type: 'success',
                  duration: 2000
                })
                this.getData()
              })
            }
          } else {
            this.$message.error('学习卡创建失败')
            return false
          }
        })
      },
      deleteStudyCard(row) {
        this.$confirm('真的要删除该批次充值卡吗？', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteBatchStudyCard(row.id, 'studyCard').then(res => {
            this.$notify({
              title: '成功',
              message: '学习卡已删除！',
              type: 'success',
              duration: 2000
            })
            this.getData()
          })
        }).catch(() => {
          this.$message.info('取消')
        })
      },
      handleSizeChange(val) {
        this.currentpage = 1
        this.pagesize = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      }
    }
  }
</script>

<style lang="scss">
  .allsearch {
    margin-top: 0;
    padding: 0;

    .el-dialog {
      border-radius: 6px;

      .foot {
        margin-top: 20px;
        padding: 15px 15px;
        border-radius: 5px;
        background-color: #d9edf7;
        color: #326f8f;
        border-left: 5px solid #50bfff;

        ul {
          text-decoration: none;
          margin: 0;
          padding: 0;
          list-style: none;

          li {
            margin-top: 5px;
          }
        }
      }
    }

    .search-content {
      width: 100%;
    }
  }
</style>
